package fei.typhoon.engine.android;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import fei.typhoon.engine.graphics.FeiSurface;
import fei.typhoon.engine.load.BitmapLoad;
import fei.typhoon.engine.load.FeiBitmap;
import fei.typhoon.engine.logic.FeiLogic;
import fei.typhoon.engine.utils.FeiArrayList;
import fei.typhoon.engine.utils.FeiUtils;

public abstract class FeiScreen extends Activity {

	public static final byte SCREEN_ANIM_FADE = 1;
	public static final byte SCREEN_ANIM_SLIDE = 2;

	private FrameLayout baseLayout = null;

	private FeiSurface baseView = null;

	protected FeiUtils feiUtils = null;

	protected BitmapLoad bitmaploader = null;

	protected Bundle savedInstanceState = null;

	private FeiArrayList<FeiLogic> logics = null;

	@Override
	protected final void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 保存savedInstanceState，可让自定义onCreat中使用
		this.savedInstanceState = savedInstanceState;
		screenCreate();
		Intent intent = getIntent();
		if (intent != null) {
			processMessage(intent.getBundleExtra("data"));
		}
	}

	private void screenCreate() {
		// 新建utiles
		feiUtils = new FeiUtils();
		// 初始化图片加载类
		bitmaploader = new BitmapLoad(this);
		// 初始化开发相关参数。
		initScreenUtils();
		// 在initScreenUtils()中设置过的参数，defaultScreenUtils不能还原。调用本方法使得在外部不能再次设置相关参数。
		defaultScreenUtils();
		// 填充屏幕，设置contentview
		fillScreen();
		// 根据utils的设置进行屏幕适配
		initScreenConfig();
		// 调用自定义onCreate时间
		onCreate();
		// 启动逻辑线程
		startLogics();
	}

	private void defaultScreenUtils() {
		// 如果在initScreenUtils()中进行了以下几个设置，则下面的相应设置无效，否则有效，目的是后续代码中不能对其再次设置
		feiUtils.setScreenOrientationPortrait(true);
		feiUtils.setScreenAutoAdapt(true);
		feiUtils.setDebugScreenLongSide(800);
		feiUtils.setDebugScreenShortSide(480);
		feiUtils.setKeepProportion(true);
		feiUtils.setBitmapZoomReally(false);
		feiUtils.setBitmapZoomLarge(false);
	}

	private void fillScreen() {
		// 游戏应用均使用无title，满屏的配置。
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		// 调节横竖屏
		if (feiUtils.isScreenOrientationPortrait()) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		} else {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		}
		// 初始化layout
		baseLayout = new FrameLayout(this);
		android.widget.RelativeLayout mainLayout = new android.widget.RelativeLayout(
				this);
		RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
				android.view.ViewGroup.LayoutParams.FILL_PARENT,
				android.view.ViewGroup.LayoutParams.FILL_PARENT);
		baseView = new FeiSurface(this);
		mainLayout.addView(baseView, relativeParams);
		baseLayout.addView(mainLayout);
		// 设置layout
		setContentView(baseLayout);
	}

	private void initScreenConfig() {
		int screenW, screenH;
		DisplayMetrics display = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(display);
		screenW = display.widthPixels;
		screenH = display.heightPixels;
		// 初始化FeiUtils中的屏幕相关参数
		feiUtils.setScreenWidth(screenW);
		feiUtils.setScreenHeight(screenH);
		if (feiUtils.isScreenOrientationPortrait()) {
			if (feiUtils.isScreenAutoAdapt()) {
				feiUtils.setScaleX((float) screenW
						/ (float) feiUtils.getDebugScreenShortSide());
				feiUtils.setScaleY((float) screenH
						/ (float) feiUtils.getDebugScreenLongSide());
			}
		} else {
			if (feiUtils.isScreenAutoAdapt()) {
				feiUtils.setScaleX((float) screenW
						/ (float) feiUtils.getDebugScreenLongSide());
				feiUtils.setScaleY((float) screenH
						/ (float) feiUtils.getDebugScreenShortSide());
			}
		}
		if (feiUtils.isBitmapZoomLarge()) {
			feiUtils
					.setScale((feiUtils.getScaleX() >= feiUtils.getScaleY() ? feiUtils
							.getScaleX()
							: feiUtils.getScaleY()));
		} else {
			feiUtils
					.setScale((feiUtils.getScaleX() <= feiUtils.getScaleY() ? feiUtils
							.getScaleX()
							: feiUtils.getScaleY()));
		}
		Log.e("FeiScreen", "------------screenW=" + getScreenWidth()
				+ ", screenH=" + getScreenHeight() + ", scale=" + getScale()
				+ ", scaleX=" + getScaleX() + ", scaleY=" + getScaleY()
				+ "-----------");
	}

	/**
	 * 调用自基类Activity的onCreate(Bundle savedInstanceState)
	 * 可在本方法中addLogic添加逻辑。这样开发者将不用在外面调用startLogics了。
	 */
	protected abstract void onCreate();

	/**
	 * 本方法中可重新设置以下参数，以下列举出默认设置
	 * 
	 * @default feiUtils.setScreenOrientationPortrait(true);
	 * @default feiUtils.setScreenAutoAdapt(true);
	 * @default feiUtils.setDebugScreenLongSide(800);
	 * @default feiUtils.setDebugScreenShortSide(480);
	 * @default feiUtils.setKeepProportion(true);
	 * @default feiUtils.setBitmapZoomReally(false);
	 * @default feiUtils.setBitmapZoomLarge(false);
	 */
	protected abstract void initScreenUtils();
	
	protected abstract void onExit();

	@Override
	protected void onPause() {
		pauseLogics();
		baseView.pause();
		super.onPause();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		baseView.resume();
		resumeLogics();
	}

	@Override
	protected final void onDestroy() {
		stopLogics();
		baseView.destroy();
		bitmaploader.release();
		onExit();
		super.onDestroy();
		System.exit(0);
	}

	public void addScene(FeiScene scene) {
		baseView.addScene(scene);
	}

	public void removeScene(FeiScene scene) {
		baseView.removeScene(scene);
	}

	public void setScene(FeiScene scene) {
		baseView.setScene(scene);
	}

	public void toScreen(Class<? extends FeiScreen> screen) {
		Intent intent = new Intent(this, screen);
		startActivity(intent);
	}

	public void toScreen(Class<? extends FeiScreen> screen, Bundle data) {
		Intent intent = new Intent(this, screen);
		intent.putExtra("data", data);
		startActivity(intent);
	}

	public void toScreen(Class<? extends FeiScreen> screen, byte animCode) {
		toScreen(screen);
		startAnimation(animCode);
	}

	public void toScreen(Class<? extends FeiScreen> screen, Bundle data,
			byte animCode) {
		toScreen(screen, data);
		startAnimation(animCode);
	}

	public void startAnimation(byte animCode) {
		int sdkVersion = android.os.Build.VERSION.SDK_INT;
		if (sdkVersion >= 5) {
			int enterAnim = android.R.anim.fade_in;
			int exitAnim = android.R.anim.fade_out;
			switch (animCode) {
			case SCREEN_ANIM_SLIDE:
				enterAnim = android.R.anim.slide_in_left;
				exitAnim = android.R.anim.slide_out_right;
				break;
			default:
				break;
			}
			overridePendingTransition(enterAnim, exitAnim);
		}
	}

	public void processMessage(Bundle data) {

	}

	// ==========================屏幕适配相关方法========================
	public boolean isScreenOrientationPortrait() {
		return feiUtils.isScreenOrientationPortrait();
	}

	public boolean isScreenAutoAdapt() {
		return feiUtils.isScreenAutoAdapt();
	}

	public boolean isKeepProportion() {
		return feiUtils.isKeepProportion();
	}

	public boolean isBitmapZoomLarge() {
		return feiUtils.isBitmapZoomLarge();
	}

	public boolean isBitmapZoomReally() {
		return feiUtils.isBitmapZoomReally();
	}

	public int getDebugScreenLongSide() {
		return feiUtils.getDebugScreenLongSide();
	}

	public int getDebugScreenShortSide() {
		return feiUtils.getDebugScreenShortSide();
	}

	public int getScreenWidth() {
		return feiUtils.getScreenWidth();
	}

	public int getScreenHeight() {
		return feiUtils.getScreenHeight();
	}

	public float getScaleX() {
		return feiUtils.getScaleX();
	}

	public float getScaleY() {
		return feiUtils.getScaleY();
	}

	public float getScale() {
		return feiUtils.getScale();
	}

	// ==========================图片资源相关方法========================
	public Bitmap resizeBitmap(Bitmap bitmap, float scaleX, float scaleY,
			boolean flag) {

		return bitmaploader.resizeBitmap(bitmap, scaleX, scaleY, flag);
	}

	public FeiBitmap getImage(int id) {

		return bitmaploader.getImage(id);
	}

	public FeiBitmap getImage(String name) {

		return bitmaploader.getImage(name);
	}

	public void storeImage(int id, FeiBitmap bitmap) {
		bitmaploader.storeImage(id, bitmap);
	}

	public void storeImage(String name, FeiBitmap bitmap) {
		bitmaploader.storeImage(name, bitmap);
	}

	public void disposeImage(int id) {
		bitmaploader.disposeImage(id);
	}

	public void disposeImage(String name) {
		bitmaploader.disposeImage(name);
	}

	// ==========================逻辑控制相关方法========================
	public void addLogic(FeiLogic logic) {
		if (logics == null) {
			logics = new FeiArrayList<FeiLogic>();
		}
		if (logic != null && !logics.contains(logic)) {
			logics.add(logic);
		}
	}

	public void startLogic(FeiLogic logic) {
		addLogic(logic);
		if (logic != null && !logic.isAlive()) {
			logic.start();
		}
	}

	public void stopLogic(FeiLogic logic) {
		if (logic != null) {
			logic.stopLogic();
		}
		if (logics == null) {
			return;
		}
		if (logics.contains(logic)) {
			logics.remove(logic);
		}
	}

	public void startLogics() {
		if (logics == null) {
			return;
		}
		logics.resetNext();
		while (logics.hasNext()) {
			FeiLogic logic = logics.getNext();
			if (logic != null && !logic.isAlive()) {
				logic.start();
			}
		}
	}

	public void resumeLogics() {
		if (logics == null) {
			return;
		}
		logics.resetNext();
		while (logics.hasNext()) {
			FeiLogic logic = logics.getNext();
			logic.resumeLogic();
		}
	}

	public void pauseLogics() {
		if (logics == null) {
			return;
		}
		logics.resetNext();
		while (logics.hasNext()) {
			FeiLogic logic = logics.getNext();
			logic.pauseLogic();
		}
	}

	public void stopLogics() {
		if (logics == null) {
			return;
		}
		logics.resetNext();
		while (logics.hasNext()) {
			FeiLogic logic = logics.getNext();
			logic.stopLogic();
		}
		logics.clear();
	}

}
